package com.wt.springsamples.security;

import com.wt.springsamples.model.SysFunction;
import com.wt.springsamples.model.SysMenu;
import com.wt.springsamples.model.SysUser;
import com.wt.springsamples.security.dto.LoginUser;
import com.wt.springsamples.biz.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private ISysUserService sysUserService;

    @Override
    public LoginUser loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.selectByLoginName(username);
        if(sysUser ==null){
            throw new BadCredentialsException("账号或密码错误！");
        }
        //获取权限
        List<SysFunction>  functionList = sysUserService.getSysFunctionListByUserId(sysUser.getId());
        List<String>  authorities = functionList.stream().filter(item -> StringUtils.hasText(item.getCode()) && StringUtils.hasText(item.getPath()))
                .map(item -> item.getCode()).collect(Collectors.toList());
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>(authorities.size());
        for (String authority : authorities) {
            grantedAuthorities.add(new SimpleGrantedAuthority(authority));
        }
//        List<GrantedAuthority> grantedAuthorities = Collections
//                .unmodifiableList(AuthorityUtils.createAuthorityList("user:delete"));
        LoginUser loginUser = new LoginUser(sysUser,grantedAuthorities);
        return loginUser;
    }
}
